// 判断arr是否为一个数组，返回一个bool值 
export const isArray = (arr) => Object.prototype.toString.call(arr) === '[object Array]'

// 深度克隆
export function deepClone(obj) {
	if ([null, undefined, Number.NaN, false].includes(obj))
		return obj
	if (typeof obj !== 'object' && typeof obj !== 'function')
		return obj
	const o = isArray(obj) ? [] : {}
	for (const i in obj) {
		if (Object.hasOwnProperty.call(obj, i))
			o[i] = typeof obj[i] === 'object' ? deepClone(obj[i]) : obj[i]
	}
	return o
}

export function timeFormat(timestamp = null, fmt = 'yyyy-MM-dd hh:mm:ss') {
	timestamp = Number.parseInt(timestamp)
	// 如果为null,则格式化当前时间
	if (!timestamp)
		timestamp = Number(new Date())
	// 判断用户输入的时间戳是秒还是毫秒,一般前端js获取的时间戳是毫秒(13位),后端传过来的为秒(10位)
	if (timestamp.toString().length === 10)
		timestamp *= 1000
	const date = new Date(timestamp)
	let ret
	const opt = {
		'y+': date.getFullYear().toString(), // 年
		'M+': (date.getMonth() + 1).toString(), // 月
		'd+': date.getDate().toString(), // 日
		'h+': date.getHours().toString(), // 时
		'm+': date.getMinutes().toString(), // 分
		's+': date.getSeconds().toString(), // 秒
	}
	for (const k in opt) {
		ret = new RegExp(`(${k})`).exec(fmt)
		if (ret)
			fmt = fmt.replace(ret[1], ret[1].length === 1 ? opt[k] : opt[k].padStart(ret[1].length, '0'))
	}
	return fmt
}

export function getDateRange(date, rule, direction = 1) {
	const startDate = new Date(date)
	const endDate = new Date(startDate)
	const o = {
		y: 'FullYear',
		M: 'Month',
		d: 'Date',
		h: 'Hours',
		m: 'Minutes',
		s: 'Seconds',
		S: 'Milliseconds',
	}
	for (const key in o) {
		const reg = new RegExp(`([0-9]+)${key}`)
		const method = o[key]
		if (reg.test(rule)) {
			const match = rule.match(reg)
			const num = match[1] >> 0
			const matchStr = match[0]
			rule = rule.replace(matchStr, '')
			endDate[`set${method}`](endDate[`get${method}`]() + num * direction)
		}
	}
	return endDate
}

export function isLeap(year) {
	if ((year % 4 === 0 && year % 100 !== 0) || (year % 400 === 0))
		return true

	return false
}


export function isEmpty(value) {
	switch (typeof value) {
		case 'undefined':
			return true
		case 'string':
			if (value.replace(/(^[ \t\n\r]*)|([ \t\n\r]*$)/g, '').length === 0)
				return true
			break
		case 'boolean':
			if (!value)
				return true
			break
		case 'number':
			if (value === -1 || isNaN(value))
				return true
			break
		case 'object':
			if (value === null || value.length === 0)
				return true
			// eslint-disable-next-line no-unreachable-loop
			for (const _i in value)
				return false

			return true
	}
	return false
}

export function pullAuth(scope, successCallback, failCallback) {
  const map = new Map([
    // ['scope.userInfo', '用户信息'],
    ['scope.userLocation', '地理位置'],
    // ['scope.userLocationBackground', '后台定位'],
    // ['scope.address', '通信地址'],
    // ['scope.record', '录音功能'],
    ['scope.writePhotosAlbum', '保存到相册'],
    // ['scope.camera', '摄像头'],
    // ['scope.invoice', '获取发票'],
    // ['scope.invoiceTitle', '发票抬头'],
    // ['scope.werun', '微信运动步数'],
  ])
  uni.getSetting({
    success(res) {
      if (!res.authSetting[scope]) {
        uni.authorize({
          scope,
          success() { // 允许授权
            successCallback()
          },
          fail() { // 拒绝授权
            if (map.has(scope)) {
              const word = map.get(scope)
              uni.showModal({
                content: `检测到您没打开${word}权限，是否去设置打开？`,
                confirmText: '确认',
                cancelText: '取消',
                success: (res) => {
                  if (res.confirm) {
                    uni.openSetting({
                      success: (res) => {
                        successCallback()
                      },
                      fail: () => {
                        failCallback()
                      },
                    })
                  }
                  else {
                    failCallback()
                  }
                },
              })
            }
            else {
              uni.showToast({
                title: '无此授权功能',
                icon: 'none',
              })
              failCallback()
            }
          },
        })
      }
      else {
         successCallback()
      }
    },
  })
}
